package howl.Servlets.cron;

import howl.model.Model;
import howl.model.PMF;
import howl.types.*;
import howl.types.query.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import compiler.exceptions.HowlModelException;
import compiler.terminals.expression.Node;

import twitter4j.Twitter;
import twitter4j.TwitterException;

@SuppressWarnings("serial")
public class CheckAlarm extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query query = pm.newQuery("select from howl.types.Alarm "
				+ "import howl.types.Alarm;");

		List<Alarm> result = (List<Alarm>) query.execute();
		Model m;
		HowlUser hu;
		for (int i = 0; i < result.size(); i++) {
			Alarm a = result.get(i);
			hu = Model.getHowlUserfromUser(a.getOwner());
			m = new Model(hu);

			ResultSet rs;
			try {
				Node n = a.getExp();
				rs = m.query(a.getFeedname(), n);

				ArrayList<Result> r = new ArrayList<Result>(rs.getResults()
						.values());
				Collections.sort(r);

				if (r.size() > 0) {
					Date e = new Date();
					e.setHours(e.getHours() - 1);
					if (r.get(0).getTimestamp().after(e)) {

						Properties props = new Properties();
						Session session = Session.getDefaultInstance(props,
								null);

						Message msg = new MimeMessage(session);
						msg.setFrom(new InternetAddress(
								"UoWhowl@googlemail.com", "Howl Admin"));
						msg.addRecipient(Message.RecipientType.TO,
								new InternetAddress(hu.getEmailAddress(), hu
										.getUsers().getNickname()));
						msg.setSubject("An alarm was triggered on Howl");
						msg.setText("The Alarm \"" + a.getExp()
								+ " \" was triggered on Howl.");
						Transport.send(msg);

					}
				}
			} catch (HowlModelException e3) {
				// TODO Auto-generated catch block
				e3.printStackTrace();
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	private String[] subArray(int start, int end, String[] s) {
		String[] ret = new String[end + 1 - start];
		for (int i = 0; i < end + 1 - start; i++) {
			ret[i] = s[start + i];
		}

		return ret;
	}
}
